using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
using Random = UnityEngine.Random;

public class Player : MonoBehaviour
{
    public int minAtk = 10;
    public int maxAtk = 12;
    public int health = 20;
    public int minDefense = 10;
    public int maxDefense = 12;
    public float attackInterval = 10f;
    private float attackTimeCount = 0f;
    private int curHealth;

    private Animator animator;

    private PlayerController playerController;

    //正在战斗的怪物
    private Monster monster;

    //伤害值
    private int woundValue;

    private Direction direction;
    // Start is called before the first frame update
    
    private void Awake()
    {
        animator = GetComponent<Animator>();
        playerController = GetComponent<PlayerController>();
    }

    void Start()
    {
        Initialize();
    }

    private void Update()
    {
        attackTimeCount += Time.deltaTime;
    }


    private void Initialize()
    {
        curHealth = health;
    }

    public void Attack(Monster monster, Direction direction)
    {
        if (attackTimeCount < attackInterval) return;
        this.monster = monster;
        this.direction = direction;
        animator.SetTrigger("Attack" + direction);
        woundValue = Random.Range(minAtk, maxAtk + 1) -
                         Random.Range(monster.monsterDetailSO.minDefense, monster.monsterDetailSO.minDefense + 1);
        if (woundValue <= 0)
        {
            woundValue = 1;
        }

        //monster.Wound(woundValue);
        attackTimeCount = 0;
    }

    public void Wound(int value)
    {
        this.curHealth -= value;
        print("玩家损失" + value);
        var infoPanel = (InfoPanel)UIManager.Instance.panelDict[UIConst.InfoPanel];
        infoPanel.UpdateHealthImg(this.curHealth);
        if (this.curHealth < 0)
        {
            this.curHealth = 0;
        }
    }

    public bool IsAlive()
    {
        return curHealth > 0;
    }

    private void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag.Equals("Monster"))
        {
            Direction direction = Direction.Right;
            if (playerController.moveInput.x != 0)
            {
                direction = playerController.moveInput.x > 0 ? Direction.Right : Direction.Left;
            }
            else if (playerController.moveInput.y != 0)
            {
                direction = playerController.moveInput.y > 0 ? Direction.Up : Direction.Down;
            }
            monster=other.gameObject.GetComponent<Monster>();
            BattleSystem.Instance.SetMonster(monster, direction);
            BattleSystem.Instance.StartBattle();
        }
    }

    public void MonsterHurt()
    {
        if (monster!=null)
        {
            monster.Wound(woundValue);
            monster = null;
        }
    }
}